package com.ywyself.controller.interceptor;

import javax.servlet.http.HttpServletRequest;

import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.core.Controller;
import com.jfinal.kit.StrKit;
import com.ywyself.common.YsConfig;
import com.ywyself.controller.SessManager;
import com.ywyself.ext.kit.YsKit;
import com.ywyself.ext.utils.YsRequestUtils;
import com.ywyself.ext.utils.YsStringUtils;
import org.junit.Test;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

public class SessionInterceptor implements Interceptor {
    @Override
    public void intercept(Invocation inv) {
        Controller c = inv.getController();
        if (SessManager.getSession(c) == null) {
            if (YsRequestUtils.isAjaxRequest(c.getRequest())) {
                YsKit.fail().msg("登录失效，请重新登录").render(c);
            } else {
                HttpServletRequest request = c.getRequest();
                String url = request.getRequestURI();
                String queryString = request.getQueryString();
                if (!StrKit.isBlank(queryString)) {
                    url = url + "?" + queryString;
                }
                StringBuilder sb = new StringBuilder().append(YsConfig.ADMIN_URL);
                try {
                    sb.append("?url=").append(URLEncoder.encode(url, "UTF8"));
                } catch (UnsupportedEncodingException e) {
                    sb.append("?url=").append(url);
                }
                c.redirect(sb.toString());
            }
        } else {
            c.setAttr("user", SessManager.getSession(inv.getController()));
            inv.invoke();
        }
    }
}
